﻿/*
Copyright © 2011 Nokia Corporation. All rights reserved.
Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
Java and all Java-based marks are trademarks or registered trademarks of 
Sun Microsystems, Inc. Other product and company names mentioned herein may be 
trademarks or trade names of their respective owners.

Subject to the conditions below, you may, without charge:

·  Use, copy, modify and/or merge copies of this software and 
   associated content and documentation files (the “Software”)

·  Publish, distribute, sub-licence and/or sell new software 
   derived from or incorporating the Software.

Some of the documentation, content and/or software maybe licensed under open source software or other licenses.  To the extent such documentation, content and/or software are included, licenses and/or other terms and conditions shall apply in addition and/or instead of this notice. The exact terms of the licenses, disclaimers, acknowledgements and notices are reproduced in the materials provided.

This file, unmodified, shall be included with all copies or substantial portions
of the Software that are distributed in source code form.

The Software cannot constitute the primary value of any new software derived 
from or incorporating the Software.

Any person dealing with the Software shall not misrepresent the source of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Microsoft.Phone.Tasks;
using System.Windows.Controls.Primitives;

namespace Carpool
{
    public partial class Carpools : UserControl, KarpoDialog
    {
        private ObservableCollection<String> carpoolnames = null;
        private ObservableCollection<String> membernames = null;

        private ObservableCollection<CheckBox> dataclouduserslist = null;

        private DCCarPoolList dccarpoollist = null;
        DCUserList dcuserlist = null;

        private int currentcarpoolind = -1;
        private string currentcarpoolstate = "none"; // "modify", "new"

        public Carpools()
        {
            InitializeComponent();


            carpoolnames = new ObservableCollection<String>();
            carpoolsCombo.DataContext = carpoolnames;
            currentcarpoolind = -1;

            membernames = new ObservableCollection<String>();
            membersCombo.DataContext = membernames;


            dataclouduserslist = new ObservableCollection<CheckBox>();
            memberselectionList.DataContext = dataclouduserslist;
        }

        internal void mainpageSizeChanged(double w, double h)
        {
            carpoolPage.Width = w; 
            carpoolPage.Height = h;

            memberselectionPage.Width = w;
            memberselectionPage.Height = h; 

            messagesending.messagesendingPage.Width = w;
            messagesending.messagesendingPage.Height = h;
            
        }

        // KarpoDialog::showDialog
        public void showDialog(bool show)
        {
            carpoolnames.Clear();
            membernames.Clear();
            carpoolnametextbox.Text = "";
            carpooldescriptiontextbox.Text = "";
            routenametextblock.Text = "<not set>";

            MainPage.main.setWindowTitle("Carpools");
            buttonEnables(false, true, false, false);
            carpoolPopup.IsOpen = show; 

            if (show)
            {
                // load the carpools ...
                KarpoMessageBox.showMessageBox("Loading saved carpools...");

                dccarpoollist = new DCCarPoolList(MainPage.userkarpoid, null);
                DC.DataCloud().GetCarpoolsByOwner(dccarpoollist, getcarpoolscb);

            }
        }

        private void buttonEnables(bool modifyb, bool newb, bool saveb, bool cancelb)
        {
            modifyButton.IsEnabled = modifyb;
            newButton.IsEnabled = newb;
            saveButton.IsEnabled = saveb;
            cancelButton.IsEnabled = cancelb;
        }

        internal void getcarpoolscb(bool isok, string errormsg, DCCarPoolList dccarpools)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccarpools.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccarpools.errorString);
            }
            else
            {
                dccarpoollist = dccarpools;
                int tempcurrentcarpoolind = currentcarpoolind;
                carpoolnames.Clear(); // this makes currentcarpoolind to -1, that is why the temp is defined
                currentcarpoolind = tempcurrentcarpoolind;
                for (int i = 0; i < dccarpoollist.carpoollist.Count(); i++)
                {
                    carpoolnames.Add(dccarpoollist.carpoollist[i].name);
                }

                if (dccarpoollist.carpoollist.Count() > 0)
                {
                    if (currentcarpoolind > -1 && currentcarpoolind < dccarpoollist.carpoollist.Count())
                    {
                        carpoolsCombo.SelectedIndex = currentcarpoolind;
                    }
                    else
                    {
                        carpoolsCombo.SelectedIndex = 0;
                    }
                }
                KarpoMessageBox.hideMessageBox();
                currentcarpoolstate = "none";

                if ((Application.Current as Carpool.App).restoreui != null && (Application.Current as Carpool.App).restoreui.appcase == "carpool")
                {
                    carpoolsCombo.SelectedIndex = (Application.Current as Carpool.App).restoreui.currentcarpoolind;
                    (Application.Current as Carpool.App).restoreui = new RestoreUI("empty");
                }
            }
        }

        // KarpoDialog::menuCommand
        public void menuCommand(string command)
        {

            if (command == "Add members...")
            {
                if (currentcarpoolind < 0)
                {
                    KarpoMessageBox.showMessageBox("Select a carpool before adding members.");
                }
                else
                {
                    if (dataclouduserslist != null)
                    {
                        for (int i = 0; i < dataclouduserslist.Count(); i++)
                        {
                            dataclouduserslist[i].IsChecked = false;
                        }
                    }

                    MainPage.appcase = "carpool-memberselection";
                    carpoolPopup.IsOpen = false;
                    memberselectionPage.Visibility = Visibility.Visible;
                }
            }
            else if (command == "Send invitations...")
            {
                sendInvitations();
            }
            else if (command == "Send message...")
            {
                if (currentcarpoolind < 0)
                {
                    KarpoMessageBox.showMessageBox("Select a carpool before sending message.");
                }
                else
                {
                    // find out the carpool's members' karpoid
                    List<String> memberlist = new List<String>();
                    for (int i = 0; i < dccarpoollist.carpoollist[currentcarpoolind].members.Count(); i++)
                    {
                        if (dccarpoollist.carpoollist[currentcarpoolind].members[i].status == "accepted")
                        {
                            memberlist.Add(dccarpoollist.carpoollist[currentcarpoolind].members[i].memberkarpoid);
                        }                    
                    }
                    if (memberlist.Count() == 0)
                    {
                        KarpoMessageBox.showMessageBox("No accepted members!");
                    }
                    else
                    {
                        carpoolPopup.IsOpen = false;
                        MainPage.appcase = "carpool-messagesending";
                        messagesending.setReceivers(memberlist);
                        messagesending.messagesendingPopup.IsOpen = true;
                    }
                }
            }
            else if (command == "Activate...")
            {
                int selectedind = carpoolsCombo.SelectedIndex;
                if (selectedind < 0)
                {
                    KarpoMessageBox.showMessageBox("Select a carpool first.");
                }
                else
                {
                    carpooactivation.IsOpen = true;
                    KarpoMessageBox.showMessageBox("Loading the current activation status...");

                    DCCarPoolActivationList dccarpoolactivationlist = new DCCarPoolActivationList();
                    DCCarPoolActivation dccarpoolactivation = new DCCarPoolActivation(dccarpoollist.carpoollist[selectedind].carpoolkarpoid);
                    dccarpoolactivationlist.carpoolactivationlist = new DCCarPoolActivation[] { dccarpoolactivation };

                    DC.DataCloud().GetCarPoolActivation(dccarpoolactivationlist, carpoolactivationcb);

                }
            }
            else if (command == "Delete carpool...")
            {
                int selectedind = carpoolsCombo.SelectedIndex;
                if (selectedind < 0 || dccarpoollist.carpoollist.Length == 0)
                {
                    KarpoMessageBox.showMessageBox("Nothing selected!");
                }
                else
                {
                    String confmsg = "Do you want to delete " + dccarpoollist.carpoollist[selectedind].name;
                    KarpoMessageBox.showMessageBoxOkCancel(confmsg, deleteCarpoolConfirmationcb);
                }
            }
            else if (command == "Delete member...")
            {                
                int selectedind = carpoolsCombo.SelectedIndex;
                int i = membersCombo.SelectedIndex;
                if (selectedind < 0 || dccarpoollist.carpoollist[selectedind].members.Count() == 0 || i < 0)
                {
                    KarpoMessageBox.showMessageBox("Nothing selected!");
                }
                else
                {
                    String confmsg = "Do you want to delete " + dccarpoollist.carpoollist[selectedind].members[i].lastname + ", " + dccarpoollist.carpoollist[selectedind].members[i].firstname;
                    KarpoMessageBox.showMessageBoxOkCancel(confmsg, deleteMemberConfirmationcb);
                }


            }
            else if (command == "Back")
            {
                if (MainPage.appcase == "carpool-messagesending")
                {
                    MainPage.appcase = "carpool";
                    messagesending.messagesendingPopup.IsOpen = false;
                    carpoolPopup.IsOpen = true;
                }
                else
                {
                    MainPage.main.resetMenu();
                    carpoolPopup.IsOpen = false;
                }
            }
                // memberselection dialog
            else if (command == "Contacts...")
            {

            }
            else if (command == "Members...")
            {
                KarpoMessageBox.showMessageBox("Get Carpool members...");
                DC.DataCloud().GetDataCloudUsers(new DCUserList("1*", true, true, true, false, null), getdatacloudusercb);
            }
            else if (command == "OK")
            {

                MainPage.appcase = "carpool";
                memberselectionPage.Visibility = Visibility.Collapsed;
                carpoolPopup.IsOpen = true;

                KarpoMessageBox.showMessageBox("Saving the memberslist");

                // some testing ...
                int selectioncount = 0;
                for (int i = 0; i < dataclouduserslist.Count(); i++)
                {

                    if ((bool)dataclouduserslist[i].IsChecked)
                    {
                        selectioncount++;
                    }
                }

                if (selectioncount == 0)
                {
                    KarpoMessageBox.showMessageBox("Nothing selected!");
                }
                else
                {
                    DCCarpoolMember[] members = new DCCarpoolMember[selectioncount];
                    int ind = 0;
                    for (int i = 0; i < dataclouduserslist.Count(); i++)
                    {
                        if ((bool)dataclouduserslist[i].IsChecked)
                        {
                            DCCarpoolMember mem = new DCCarpoolMember();
                            mem.carpoolmemberkarpoid = ""; // generated in the server side => KarpoDC.doAddCarpoolMembers
                            mem.carpoolkarpoid = dccarpoollist.carpoollist[currentcarpoolind].carpoolkarpoid;
                            mem.ownerkarpoid = dccarpoollist.carpoollist[currentcarpoolind].ownerkarpoid;

                            mem.memberkarpoid = dcuserlist.userlist[i].karpoid;
                            mem.firstname = dcuserlist.userlist[i].firstname;
                            mem.lastname = dcuserlist.userlist[i].lastname;
                            mem.phone = dcuserlist.userlist[i].phone;
                            mem.hometown = dcuserlist.userlist[i].hometown;
                            mem.status = "uninvited";
                            mem.picklat = "0";
                            mem.picklon = "0";

                            members[ind] = mem;
                            ind++;
                        }
                    }


                    DCCarPoolMembersList dcmemberlist = new DCCarPoolMembersList(MainPage.userkarpoid, members);
                    DC.DataCloud().AddCarpoolMembers(dcmemberlist, carpoolmemberslistcb);
                }
                

            }
            else if (command == "Cancel")
            {
                MainPage.appcase = "carpool";
                memberselectionPage.Visibility = Visibility.Collapsed; 
                carpoolPopup.IsOpen = true;
 
            }

        }

        internal void deleteMemberConfirmationcb(int button)
        {
            if (button == KarpoMessageBox.OK_BUTTON)
            {
                int selectedind = carpoolsCombo.SelectedIndex;
                int i = membersCombo.SelectedIndex;

                DCKarpoIdList idlist = new DCKarpoIdList(MainPage.userkarpoid, MainPage.userpassword, MainPage.username);
                idlist.karpoids = new string[] { dccarpoollist.carpoollist[selectedind].members[i].carpoolmemberkarpoid };

                KarpoMessageBox.showMessageBox("Removing member...");
                DC.DataCloud().DeleteCarpoolMembers(idlist, deletecarpoolmembercb);
            }
        }

        internal void deleteCarpoolConfirmationcb(int button)
        {
            if (button == KarpoMessageBox.OK_BUTTON)
            {
                int selectedind = carpoolsCombo.SelectedIndex;
                if (selectedind < 0 || dccarpoollist.carpoollist.Length == 0)
                {
                    KarpoMessageBox.showMessageBox("Nothing selected!");
                }
                else
                {
                    KarpoMessageBox.showMessageBox("Deleting selected carpool...");
                    DCCarPoolList dccplist = new DCCarPoolList();
                    dccplist.karpoid = MainPage.userkarpoid;
                    dccplist.password = MainPage.userpassword;
                    dccplist.carpoollist = new DCCarPool[] { dccarpoollist.carpoollist[selectedind] };
                    DC.DataCloud().DeleteCarpool(dccplist, deletecarpoolcb);
                }
            }
        }

        internal void deletecarpoolcb(bool isok, string errormsg, DCCarPoolList dccplist)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccplist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccplist.errorString);
            }
            else
            {
                // get the updated carpoollist
                System.Threading.Thread.Sleep(2000); // first wait for 2 secs so that the server gets the saved data in the database

                dccarpoollist = new DCCarPoolList(MainPage.userkarpoid, null);
                DC.DataCloud().GetCarpoolsByOwner(dccarpoollist, getcarpoolscb);
            }
        }

        internal void deletecarpoolmembercb(bool isok, string errormsg, DCKarpoIdList dckarpoidlist)
        {

            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dckarpoidlist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dckarpoidlist.errorString);
            }
            else if (dckarpoidlist.karpoids.Count() > 0)
            {
                membernames.Clear();
                int selectedind = carpoolsCombo.SelectedIndex;
                int memcount = dccarpoollist.carpoollist[selectedind].members.Count() - 1;

                DCCarpoolMember[] members = new DCCarpoolMember[memcount];
                int m = 0;
                for (int i = 0; i < dccarpoollist.carpoollist[selectedind].members.Count(); i++)
                {
                    if (dccarpoollist.carpoollist[selectedind].members[i].carpoolmemberkarpoid.CompareTo(dckarpoidlist.karpoids[0]) != 0)
                    {
                        members[m] = dccarpoollist.carpoollist[selectedind].members[i];

                        String item = members[m].lastname + ", " + members[m].firstname + " [" + members[m].status + "]";
                        membernames.Add(item);

                        m++;
                    }
                }

                dccarpoollist.carpoollist[selectedind].members = members;

                KarpoMessageBox.hideMessageBox();
            }
        }

        internal void carpoolmemberslistcb(bool isok, string errormsg, DCCarPoolMembersList dccarpoolmemberslist)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccarpoolmemberslist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccarpoolmemberslist.errorString);
            }
            else
            {
                // get the updated carpoollist
                System.Threading.Thread.Sleep(2000); // first wait for 2 secs so that the server gets the saved data in the database

                dccarpoollist = new DCCarPoolList(MainPage.userkarpoid, null);
                DC.DataCloud().GetCarpoolsByOwner(dccarpoollist, getcarpoolscb);
            }
        }

        internal void getdatacloudusercb(bool isok, string errormsg, DCUserList dcusers)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dcusers.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dcusers.errorString);
            }
            else
            {
                dcuserlist = dcusers;
                // populate memmberselection list 
                dataclouduserslist.Clear();
                for (int u = 0; u < dcuserlist.userlist.Length; u++)
                {
                    CheckBox cbox = new CheckBox();
                    cbox.FontFamily = new FontFamily("Arial");
                    cbox.FontSize = 16;
                    cbox.Foreground = MainPage.BlackColor;
                    cbox.BorderBrush = MainPage.BlackColor;
                    cbox.BorderThickness = new Thickness(1);
                    cbox.Content = dcuserlist.userlist[u].lastname + ", " + dcuserlist.userlist[u].firstname + " " + dcuserlist.userlist[u].phone + ", " + dcuserlist.userlist[u].hometown;
                    dataclouduserslist.Add(cbox);
                }

                KarpoMessageBox.hideMessageBox();
                currentcarpoolstate = "none";
            }
        }

        // KarpoDialog::crosshairLocation
        public void crosshairLocation(double lat, double lon)
        {
            
        }

        private void carpoolsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            currentcarpoolind = -1;
            int selectedind = carpoolsCombo.SelectedIndex;
            if (selectedind > -1 && dccarpoollist.carpoollist != null && selectedind < dccarpoollist.carpoollist.Count())
            {
                carpoolnametextbox.Text = dccarpoollist.carpoollist[selectedind].name;
                carpooldescriptiontextbox.Text = dccarpoollist.carpoollist[selectedind].description;
 
                if (dccarpoollist.carpoollist[selectedind].routekarpoid == "<not set>" || dccarpoollist.carpoollist[selectedind].routekarpoid == "0")
                {
                    dccarpoollist.carpoollist[selectedind].routekarpoid = "0";
                    dccarpoollist.carpoollist[selectedind].routename = "<not set>";
                }

                routenametextblock.Text = dccarpoollist.carpoollist[selectedind].routename;

                membernames.Clear();
                for (int i = 0; i < dccarpoollist.carpoollist[selectedind].members.Count(); i++)
                {
                    String item = dccarpoollist.carpoollist[selectedind].members[i].lastname + ", " +
                        dccarpoollist.carpoollist[selectedind].members[i].firstname + " [" +
                        dccarpoollist.carpoollist[selectedind].members[i].status + "]";
                    membernames.Add(item);
                }

                buttonEnables(true, true, false, false);
                currentcarpoolind = selectedind;
            }
        }

        private void modifyButton_Click(object sender, RoutedEventArgs e)
        {
            buttonEnables(false, false, true, true);
            currentcarpoolstate = "modify"; 
        }

        private void newButton_Click(object sender, RoutedEventArgs e)
        {
            carpoolsCombo.SelectedIndex = -1;
            currentcarpoolind = -1;
            membernames.Clear();
            carpoolnametextbox.Text = "";
            carpooldescriptiontextbox.Text = "";
            routenametextblock.Text = "<not set>";
            buttonEnables(false, false, true, true);
            currentcarpoolstate = "new"; 
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            if (carpoolnametextbox.Text == "")
            {
                KarpoMessageBox.showMessageBox("Name is missing!");
            }
            else
            {
                KarpoMessageBox.showMessageBox("Saving the carpool...");
                if (currentcarpoolstate == "new")
                {
                    DCCarPool newcp = new DCCarPool(MainPage.userkarpoid, "", carpoolnametextbox.Text, carpooldescriptiontextbox.Text, "0", "<not set>", new DCCarpoolMember[] { });
                    // Note that the carpoolkarpoid for the new carpool is generated in the server side

                    DCCarPool[] cparr = new DCCarPool[dccarpoollist.carpoollist.Length + 1];

                    Array.Copy(dccarpoollist.carpoollist, cparr, dccarpoollist.carpoollist.Length);
                    cparr[dccarpoollist.carpoollist.Length] = newcp;

                    dccarpoollist.carpoollist = cparr;

                    DC.DataCloud().SaveCarpools(dccarpoollist, getcarpoolscb);

                }
                else if (currentcarpoolstate == "modify")
                {
                    int selind = carpoolsCombo.SelectedIndex;
                    if (selind > -1)
                    {
                        dccarpoollist.carpoollist[selind].name = carpoolnametextbox.Text;
                        dccarpoollist.carpoollist[selind].description = carpooldescriptiontextbox.Text;
                        DC.DataCloud().SaveCarpools(dccarpoollist, getcarpoolscb);

                    }
                    else
                    {
                        buttonEnables(false, true, false, false);
                        currentcarpoolstate = "none";
                    }
                }
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            buttonEnables((carpoolsCombo.SelectedIndex > -1), true, false, false);
            if (dccarpoollist.carpoollist.Count() > 0)
            {
                carpoolsCombo.SelectedIndex = 0;
            }
            currentcarpoolstate = "none";
        }

        
        String invitationstring = "Hi! Want to join my carpool? More information from the attached link. ";
        String memberphone = "";
        String carpoolmemberkarpoid = "";

        private void sendInvitations()
        {
            carpoolmemberkarpoid = "";

            int cpindex = carpoolsCombo.SelectedIndex;

            int m = 0;
            while (m < dccarpoollist.carpoollist[cpindex].members.Length && carpoolmemberkarpoid == "")
            {
                if (dccarpoollist.carpoollist[cpindex].members[m].status == "uninvited")
                {
                    carpoolmemberkarpoid = dccarpoollist.carpoollist[cpindex].members[m].carpoolmemberkarpoid;
                    memberphone = dccarpoollist.carpoollist[cpindex].members[m].phone;
                }
                else
                {
                    m++;
                }
            }

            if (carpoolmemberkarpoid == "")
            {
                KarpoMessageBox.showMessageBox("There is no uninvited members.");
            }
            else
            {
                KarpoMessageBox.showMessageBox("Updating member's status...");
                dccarpoollist.carpoollist[cpindex].members[m].status = "invited";
                DC.DataCloud().SaveCarpools(dccarpoollist, updatedcarpoolscb);
            }
        }


        internal void updatedcarpoolscb(bool isok, string errormsg, DCCarPoolList dccarpools)
        {
            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccarpools.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccarpools.errorString);
            }
            else
            {
                dccarpoollist = dccarpools;
                int tempcurrentcarpoolind = currentcarpoolind;
                carpoolnames.Clear(); // this makes currentcarpoolind to -1, that is why the temp is defined
                currentcarpoolind = tempcurrentcarpoolind;
                for (int i = 0; i < dccarpoollist.carpoollist.Count(); i++)
                {
                    carpoolnames.Add(dccarpoollist.carpoollist[i].name);
                }

                if (dccarpoollist.carpoollist.Count() > 0)
                {
                    if (currentcarpoolind > -1 && currentcarpoolind < dccarpoollist.carpoollist.Count())
                    {
                        carpoolsCombo.SelectedIndex = currentcarpoolind;
                    }
                    else
                    {
                        carpoolsCombo.SelectedIndex = 0;
                    }
                }
                KarpoMessageBox.hideMessageBox();
                currentcarpoolstate = "none";

                if (memberphone.Length > 0 && carpoolmemberkarpoid.Length > 0)
                {
                    // Then the actual sending
                    KarpoMessageBox.showMessageBox("Send the invitation to " + memberphone);

                    SmsComposeTask smsComposeTask = new SmsComposeTask();
                    smsComposeTask.To = memberphone;
                    smsComposeTask.Body = invitationstring + MainPage.datacloudurl + "/Membership?id=" + carpoolmemberkarpoid;

                    memberphone = "";
                    carpoolmemberkarpoid = "";

                    RestoreUI rui = new RestoreUI("carpool");
                    rui.currentcarpoolind = currentcarpoolind;

                    (Application.Current as Carpool.App).restoreui = rui;
                  
                    smsComposeTask.Show();
                }
            }
        }



        internal void carpoolactivationcb(bool isok, string errormsg, DCCarPoolActivationList dccarpoolactivationlist)
        {

            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccarpoolactivationlist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccarpoolactivationlist.errorString);
            }
            else if (dccarpoolactivationlist.carpoolactivationlist.Count() > 0)
            {
                DCCarPoolActivation dccarpoolactivation = dccarpoolactivationlist.carpoolactivationlist[0];

                activationaliastext.Text = (String.IsNullOrEmpty(dccarpoolactivation.alias) ? MainPage.useralias : dccarpoolactivation.alias);
                if (!String.IsNullOrEmpty(dccarpoolactivation.active) && dccarpoolactivation.active.CompareTo("1") == 0)
                {
                    activationstatustext.Text = "[activated]";
                }
                else
                {
                    activationstatustext.Text = "[not activated]";
                }
                KarpoMessageBox.hideMessageBox();
            }
        }

        private void gpsonButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedind = carpoolsCombo.SelectedIndex;
            setcarpoolactivation(dccarpoollist.carpoollist[selectedind].carpoolkarpoid, "1", "0", "0", activationaliastext.Text);
            carpooactivation.IsOpen = false;
        }

        private void gpsoffButton_Click(object sender, RoutedEventArgs e)
        {
            int selectedind = carpoolsCombo.SelectedIndex;
            setcarpoolactivation(dccarpoollist.carpoollist[selectedind].carpoolkarpoid, "0", "0", "0", activationaliastext.Text);
            carpooactivation.IsOpen = false;
        }

        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            carpooactivation.IsOpen = false;
        }


        internal void setcarpoolactivation(string carpoolkarpoid, string active, string lat, string lon, string alias)
        {
            DCCarPoolActivationList dccarpoolactivationlist = new DCCarPoolActivationList();
            DCCarPoolActivation dccarpoolactivation = new DCCarPoolActivation(carpoolkarpoid);
            dccarpoolactivation.lat = lat;
            dccarpoolactivation.lon = lon;
            dccarpoolactivation.alias = alias;
            dccarpoolactivation.active = active;

            dccarpoolactivationlist.carpoolactivationlist = new DCCarPoolActivation[] { dccarpoolactivation };
            DC.DataCloud().SetCarPoolActivation(dccarpoolactivationlist, setcarpoolactivationcb);
        }

        internal void setcarpoolactivationcb(bool isok, string errormsg, DCCarPoolActivationList dccarpoolactivationlist)
        {

            if (!isok)
            {
                KarpoMessageBox.showMessageBox("Failed: " + errormsg);
            }
            if (dccarpoolactivationlist.isError)
            {
                KarpoMessageBox.showMessageBox("Failed: " + dccarpoolactivationlist.errorString);
            }
            else if (dccarpoolactivationlist.carpoolactivationlist.Count() > 0)
            {
                MainPage.dccarpoolactivation = dccarpoolactivationlist.carpoolactivationlist[0];
                KarpoMessageBox.hideMessageBox();
                
                if (MainPage.dccarpoolactivation.active.CompareTo("1") == 0)
                {
                    MainPage.main.sendGPS("start");
                }
                else
                {
                    MainPage.main.sendGPS("stop");
                }
                

            }
        }

 


    }
}
